package com.framework.shs.commom.system.intercept;

import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.framework.shs.a.entity.User;
import com.framework.shs.a.service.BaseService;
import com.framework.shs.a.service.UserService;
import com.framework.shs.commom.util.DateUtils;
import com.framework.shs.commom.util.SpringContextHolder;

public class LogInterceptor extends BaseService implements HandlerInterceptor {

	private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>(
			"ThreadLocal StartTime");

	private static final UserService userService = SpringContextHolder
			.getBean(UserService.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet
	 * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (logger.isDebugEnabled()) {
			long beginTime = System.currentTimeMillis();// 1、开始时间
			startTimeThreadLocal.set(beginTime); // 线程绑定变量（该数据只有当前请求的线程可见）
			logger.debug("开始计时: {}  URI: {}", new SimpleDateFormat(
					"hh:mm:ss.SSS").format(beginTime), request.getRequestURI());
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {// handler=default//异常
		// if (!(handler instanceof HandlerMethod)) {
		// return;
		// }
		// HandlerMethod hMethod = (HandlerMethod)handler;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 打印JVM信息。
		if (logger.isDebugEnabled()) {
			long beginTime = startTimeThreadLocal.get();// 得到线程绑定的局部变量（开始时间）
			long endTime = System.currentTimeMillis(); // 2、结束时间
			logger.debug(
					"计时结束：{}  耗时：{}  URI: {}  最大内存: {}m  已分配内存: {}m  已分配内存中的剩余空间: {}m  最大可用内存: {}m",
					new SimpleDateFormat("hh:mm:ss.SSS").format(endTime),
					DateUtils.formatDateTime(endTime - beginTime), request
							.getRequestURI(),
					Runtime.getRuntime().maxMemory() / 1024 / 1024, Runtime
							.getRuntime().totalMemory() / 1024 / 1024, Runtime
							.getRuntime().freeMemory() / 1024 / 1024, (Runtime
							.getRuntime().maxMemory()
							- Runtime.getRuntime().totalMemory() + Runtime
							.getRuntime().freeMemory()) / 1024 / 1024);
		}

	}

}
